package br.ufmg.notservice.service;

import br.ufmg.notservice.activity.NotificationConstants;
import br.ufmg.notservice.utils.AndroidUtils;
import br.ufmg.ubicomp.event.EventObject;
import android.content.Intent;
import android.os.SystemClock;
import android.util.Log;

public class EventService extends AbstractService {

	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		String s = intent.getStringExtra(NotificationConstants.EVENT_MESSAGE);
		AndroidUtils.showAlert(getApplicationContext(), "Received data: " + s);
		// handle event generated
		EventObject eo = new EventObject(s, s);
		EventHandler eh = new EventHandler(eo);
		getHandler().postAtTime(eh, System.currentTimeMillis() + 1000);
	}

	private void sendBroadcastToNotification(EventObject eo) {
		Intent intent;
		// send notification
		AndroidUtils.showAlert(this, "sending notification intent");
		intent = new Intent(NotificationConstants.NOTIFICATION_RECEIVER);
		intent.putExtra(NotificationConstants.NOTIFICATION_MESSAGE, "ok2");
		intent.putExtra(NotificationConstants.EVENT_ID, eo.getId());

		getApplicationContext().sendBroadcast(intent);
	}

	private class EventHandler implements Runnable{
		
		private EventObject eo;
		
		public EventHandler(EventObject eo) {
			super();
			this.eo = eo;
		}
		public void run(){
			long time = SystemClock.uptimeMillis();
			NotificationEventServer.getInstance().addEvent(eo);
			sendBroadcastToNotification(eo);			
		}
	};
	
}
